<?php
use Illuminate\Support\Str;
use Illuminate\Support\HtmlString;

if (! function_exists('mixs')) {

    /**
     * 获取 public 资源文件，自定义函数
     *
     * @param string $path            
     * @param string $filename            
     * @return \Illuminate\Support\HtmlString
     *
     * @throws \Exception
     */
    function mixs($path, $filename = '', $manifestDirectory = 'manifests')
    {
        static $manifests = [];
        $pathArray = [];
        
        if (! Str::startsWith($path, '/')) {
            $path = "/{$path}";
        }
        
        if ($filename && ! Str::startsWith($filename, '/')) {
            $filename = "/{$filename}";
        }
        
        $manifestDirectory = public_path($manifestDirectory);
        if (! is_dir($manifestDirectory)) {
            throw new Exception('manifests 目录不存在');
        }
        
        if ($filename) { // 文件读取
            $manifestPath = $manifestDirectory . $filename;
            
            if (! isset($manifests[$manifestPath])) {
                if (! file_exists($manifestPath)) {
                    throw new Exception("{$filename} 文件不存在");
                }
                $manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true);
            }
        } elseif (($dh = opendir($manifestDirectory)) !== false) { // 目录读取
            while (($filename = readdir($dh)) !== false) {
                if ($filename != '.' && $filename != '..') {
                    $manifestPath = "{$manifestDirectory}/{$filename}";
                    $manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true);
                }
            }
            closedir($dh);
        }
        
        foreach ($manifests as $manifest) {
            $pathArray = array_merge($pathArray, $manifest);
        }
        
        if (! isset($pathArray[$path])) {
            if (app('config')->get('app.debug')) {
                throw new Exception("未定义的 index: {$path}");
            } else {
                return $path;
            }
        }
        
        return new HtmlString($pathArray[$path]);
    }
}
